import React, { useState, useMemo, useEffect, ReactNode } from 'react';
import { getDaysOfMonth, getToday, getClasses } from './utils';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import axios from '../axios';
dayjs.locale('zh-cn');
import { Empty, List, Card, message, Popconfirm, Button } from 'antd';
import { CarryOutOutlined } from '@ant-design/icons';
import '../styles/detail.less';

export default function calendar() {
  const [month, setMonth] = useState(dayjs());
  const days = useMemo(() => {
    return getDaysOfMonth(month.year(), month.month() + 1);
  }, [month]);
  const weekTitles = useMemo(() => {
    return [...Array(7)].map((_, weekInx) => {
      return dayjs().day(weekInx);
    });
  }, []);
  const onMonthSwitch = (action: number) => {
    setMonth((month) => {
      return month.add(action, 'month');
    });
  };
  //获取班表信息
  const [id] = useState(localStorage.getItem('userId') || '');
  const [classes, setClasses] = useState<
    {
      [x: string]: ReactNode;
      job: any;
    }[]
  >([]);
  const getData = async () => {
    const data = await getClasses(id);
    const newDays = days.map((day) => {
      const matchedJob = data.find(
        (item: any) =>
          item.year === day.year() &&
          item.month === day.month() + 1 &&
          item.day === day.date(),
      );
      const newDay = { ...day, job: matchedJob };
      if (matchedJob) {
        newDay.job = matchedJob;
      }
      return newDay;
    });
    console.log(newDays);
    setClasses(newDays);
  };
  useEffect(() => {
    getData();
  }, [days]);
  //班次详情信息
  const [dayDetail, setDayDetail] = useState<any>(null);
  const onDetail = (day: any) => {
    //判断day里是否有job属性
    //如果有job属性，说明是排班日，可以查看详情
    //如果没有job属性，说明是非排班日，无法查看详情
    if (day.job) {
      setDayDetail(day);
    } else {
      setDayDetail(null);
      return;
    }
  };
  //是否打卡
  const [isChecked, setIsChecked] = useState(true);
  const onCheck = async () => {
    message.success(
      isChecked ? '上班打卡成功!祝您工作愉快!' : '下班打卡成功！祝您生活愉快',
    );
    setIsChecked(!isChecked);
    const {
      data: { code },
    } = await axios.post('/work', {
      id,
      year: dayDetail.$y,
      month: dayDetail.$M + 1,
      day: dayDetail.$D,
    });
    if (code === 200) {
      //刷新
      getData();
    }
  };
  const cancelCheck = () => {
    message.error('取消打卡！');
  };
  return (
    <div className="detail-contanier">
      <div className="detail-calendar">
        <div className="detail-calendar-title">我的排班日历</div>
        <div className="detail-switch">
          <div onClick={() => onMonthSwitch(-1)}>
            <LeftOutlined style={{ color: 'blue' }} />
          </div>
          <div>{month.format('MMM YYYY')}</div>
          <div onClick={() => onMonthSwitch(1)}>
            <RightOutlined style={{ color: 'blue' }} />
          </div>
        </div>
        <div className="detail-week">
          {weekTitles.map((title, index) => {
            return (
              <div className="detail-week-item" key={index}>
                {title.format('dd')}
              </div>
            );
          })}
        </div>
        <div className="detail-days">
          {classes.map((day, index) => {
            return (
              <div
                className={day.job ? 'active-day' : 'calendar-day'}
                key={index}
                onClick={() => {
                  onDetail(day);
                }}
              >
                {day.$D}
              </div>
            );
          })}
        </div>
      </div>

      <div className="job-detail">
        <div className="job-detail-title">值班安排</div>
        <div className="job-detail-content">
          {dayDetail ? (
            <List
              grid={{ gutter: 16, column: 1 }}
              dataSource={[dayDetail]}
              renderItem={(item: any) => (
                <List.Item>
                  <Card title={item.job.classesName}>
                    {item.job.startTime}-{item.job.endTime}
                    <br></br>
                    {'上班时间:' + item.job.workTime || ''}-
                    {'下班时间:' + item.job.endWorkTime || ''}
                  </Card>
                  <Popconfirm
                    title={
                      isChecked ? '确定要上班打卡吗？' : '确定要下班打卡吗？'
                    }
                    onConfirm={onCheck}
                    onCancel={cancelCheck}
                    okText="Yes"
                    cancelText="No"
                  >
                    <Button type="primary">
                      {isChecked ? '打卡' : '下班打卡'}
                    </Button>
                  </Popconfirm>
                </List.Item>
              )}
            />
          ) : (
            <Empty
              image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              imageStyle={{ height: 60 }}
              description={
                <span style={{ fontSize: '30px', color: 'gray' }}>
                  <CarryOutOutlined />
                  暂无排班信息<br></br>
                  享受假期！
                </span>
              }
            ></Empty>
          )}
        </div>
      </div>
    </div>
  );
}
